package com.example.lib_base.http

import okhttp3.ConnectionPool
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import java.io.IOException
import java.util.concurrent.TimeUnit

interface HttpRetrofitImpl :BaseRetrofit{
    fun createHttpCilent(): OkHttpClient.Builder{
        return OkHttpClient.Builder()
            .writeTimeout(60,TimeUnit.SECONDS)//写入超时
            .readTimeout(60,TimeUnit.SECONDS)//读取超时
            .connectTimeout(30,TimeUnit.SECONDS)//连接超时
            .connectionPool(ConnectionPool(5, 5, TimeUnit.MINUTES)) // 连接池管理
            .retryOnConnectionFailure(true) // 连接失败时重试
            .addInterceptor(RetryInterceptor(3)) // 添加重试拦截器
            .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))//日志拦截
    }
    
    // 重试拦截器
    class RetryInterceptor(private val maxRetry: Int) : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val request = chain.request()
            var response: Response? = null
            var exception: IOException? = null
            
            for (i in 0..maxRetry) {
                try {
                    response?.close() // 确保之前的响应被关闭
                    response = chain.proceed(request)
                    if (response.isSuccessful) {
                        return response
                    }
                    // 对于非成功响应，检查是否需要重试
                    if (i < maxRetry && (response.code == 502 || response.code == 503 || response.code == 504)) {
                        response.close()
                        Thread.sleep(1000L * (i + 1))
                        continue
                    }
                    return response
                } catch (e: IOException) {
                    exception = e
                    response?.close()
                    if (i == maxRetry) {
                        throw e
                    }
                    // 等待一段时间后重试
                    Thread.sleep(1000L * (i + 1))
                }
            }
            
            return response ?: throw (exception ?: IOException("Unknown error"))
        }
    }
}